<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.name" placeholder="部门名称"></el-input>
				</el-form-item>

				<el-form-item>
					<el-select v-model="filters.parentId" clearable placeholder="上级部门">
						<el-option
								v-for="item in parentDepts"
								:key="item.id"
								:label="item.name"
								:value="item.id">
						</el-option>
					</el-select>
				</el-form-item>

				<el-form-item>
					<el-select v-model="filters.managerId" clearable placeholder="部门经理">
						<el-option
								v-for="item in managers"
								:key="item.id"
								:label="item.username"
								:value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getDepartments(1)">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<!--{id sn name dirPath state manager_id parent_id manager parent} -->
		<el-table :data="dept"   @row-dblclick="yyyyy" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55"></el-table-column>
			<el-table-column type="index" width="60"></el-table-column>
			<el-table-column prop="name" label="部门名称" width="120" sortable></el-table-column>
			<el-table-column prop="state" label="状态" width="100" :formatter="formatSex" sortable>
				<template slot-scope="scope">
					<el-button type="text" size="small" @click="suppstop(scope.$index, scope.row)"
							   :type="scope.row.state === 1?'primary':'danger'"
					>
						{{scope.row.state===1?"启用":"禁用"}}
					</el-button>
				</template>

			</el-table-column>
			<el-table-column prop="sn" label="部门编号" width="120" sortable></el-table-column>
			<el-table-column prop="parent.name" label="上级部门" width="120" sortable></el-table-column>


			<el-table-column prop="manager.username" label="部门经理" width="120" sortable></el-table-column>


			<el-table-column label="操作" align="center">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="size" :total="total" :current-page="page" style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog v-bind:title="title" v-bind:visible.sync="editFormVisible" :close-on-click-modal="true">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="部门名字" prop="name">
					<el-input v-model="editForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="部门编号" prop="sn">
					<el-input v-model="editForm.sn" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="部门状态">
					<el-radio-group v-model="editForm.state">
						<el-radio class="radio" :label="1">启用</el-radio>
						<el-radio class="radio" :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="部门经理">


					<!--
					     1.v-for="emp in employees" 遍历双向绑定的：  employees 值  emp 遍历出来的每一个employee对象
					     2.:label="emp.username"  当你选中之后，显示内容
					     3.value="emp">  value 提交到 后段的值emp对象{}  选中之后的一个值
                         4.如果你的value选的是对象    一定要   select  value-key="id"
					-->
					<!--<el-input v-model="editForm.manager" auto-complete="off"></el-input>-->
					<el-select v-model="editForm.managerId" clearable placeholder="部门经理">
						<el-option
								v-for="item in employees"
								:key="item.id"
								:label="item.username"
								:value="item.id">
						</el-option>
					</el-select>



				</el-form-item>
				<el-form-item  label="上级部门" prop="">
					<!-- v-model获取选择的值
                     :props="{ checkStrictly: true ,value:'id',label:'name'}"
                                                    传递的值          给人看的
                     -->
					<el-cascader
							v-model="editForm.parentIds"
							:options="treeList"
							:props="{ checkStrictly: true ,value:'id',label:'name'}"
							clearable></el-cascader>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>


	</section>
</template>

<script>

	export default {
		data() {
			return {
				filters: {
					name: '',
					parentId: null,
					managerId: null
				},
				treeList:[],
				title: "",
				managers: [],
				parentDepts: [],
				employees: [],
				dept: [],
				total: 0,
				size: 5,
				page: 1,
				listLoading: false,
				sels: [],//列表选中列

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				editFormRules: {
					name: [
						{required: true, message: '请输入姓名', trigger: 'blur'}
					],
					sn: [
						{required: true, message: '请输入编号', trigger: 'blur'}
					]
				},
				//编辑界面数据
				editForm: {
					name: "",
					sn: "",
					state: 0,
					manager: "",
					parentIds:[],//上级部门数组


				},


				addLoading: false,


			}
		},
		methods: {
			yyyyy(row, clum, evernt) {
				console.log("table", row)
			},
			bbbbbb() {
				alert(2)
			},
			formatSex: function (row, column) {
				return row.state == 1 ? '正常' : row.state == 0 ? '禁用' : '未知';
			},
			//性别显示转换
			/*formatState: function (row, column) {//row 这一行的数据
				return row.state == 1 ? '<span style="green">启用</span>' : row.state == 0 ? '禁用' : '未知';
			},*/
			handleCurrentChange(val) {
				this.page = val;
				this.getDepartments();
			},
			//获取部门列表
			getDepartments(num) {
				if (num == 1){
					this.page = 1
				}

				let para = {
					page: this.page,

					//高级查询的条件
					keyword: this.filters.name,
					parentId: this.filters.parentId,
					managerId: this.filters.managerId
				};
				this.listLoading = true;  //状态框
				//pageList   {totalCount:"",data:[{},{}]}   json----对象
				//User id ,name {id:"",name:""}
				//Map   {}
				//List<User>    [{},{},{}]
				//result.data
				this.$http.post("/dept/pagelist", para)
						.then(result => {
							console.log("请求的分页数据---------------------------------：", result)

							this.dept = result.data.list
							this.total = result.data.total
							//关闭状态框
							this.listLoading = false;
						});
				//NProgress.start();
				/*getDepartmentListPage(para).then((res) => {
					this.total = res.data.total;
					this.departments = res.data.departments;
					this.listLoading = false;
					//NProgress.done();
				});*/
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					this.$http.delete("/dept/" + row.id)
							.then(result => {  //  result{data:AjaxResult{success:true,msg:"xxxx"}}
								this.listLoading = false;
								//let {success,msg} = result.data;//{success:true,msg:"xxxx"}
								if (result.data.success) {//成功
									this.getDepartments()
									this.$message({
										message: "操作成功",
										type: 'success'
									});
								} else {//失败
									this.$message({
										message: "操作失败",
										type: 'error'
									});
								}
							}).catch(result => {

					})


					/*removeDepartment(para).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getDepartments();
					});*/
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {

				this.title = "编辑"
				this.editFormVisible = true;
				this.editForm = Object.assign({}, row);//  把一行的数据拷贝，给到绑定的    editForm
				let arr = row.dirPath.split("/") /*    /2/5/8     [,2,5,8] */
				arr = arr.slice(1, arr.length - 1)
				for (var i in arr) {//i 索引
					arr[i] = parseInt(arr[i])
				}
				this.editForm.parentIds = arr
				console.log("111111111111111111")
				console.log(this.editForm.parentIds)
			},
			//显示新增界面
			handleAdd: function () {
				this.title = "新增"
				this.editFormVisible = true;
				this.editForm = {
					state: 1
				};
			},
			//编辑
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {//使用校验规则，校验表单是否符合校验规则
					if (valid) {// 如果为true
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;

							//NProgress.start();
							//【拷贝】了双向绑定的editForm  拿到模态框，填写的数据
							//提交的数据{id:11,name:"dept1",manager:{},parent:[2,5]}
							//提交的数据{id:11,name:"dept1",manager:{},parent:{id:5}}


							let para = Object.assign({}, this.editForm);
							let arr = para.parent
							if (arr) {//  如果我不选择上级部门们： arr undifined
								para.parent = {id: arr[arr.length - 1]}
							}
							console.log("let para = Object.assign({}, this.editForm);", para)
							this.$http.post("/dept", para)
									.then(res => {
										this.editLoading = false;
										this.editFormVisible = false;
											this.getDepartments();//操作成功，之后重新加载数据
											this.$message({
												message: res.data.success?'提交成功':res.data.message,
												type: res.data.success?'success':'error'
											});

									})


							/*para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
							editDepartment(para).then((res) => {
								this.editLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['editForm'].resetFields();
								this.editFormVisible = false;
								this.getDepartments();
							});*/
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				//map:抽取   item => item.id：把id都拿出来  组装成一个数组
				var ids = this.sels.map(item => item.id);
				console.log(ids)
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para = { ids: ids };
					this.$http.post("/dept/deleteBatch",para).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getDepartments();
					});
				}).catch(() => {

				});

			},
			/*查询所有的员工*/
			// 	getEmps(){
			// 		this.$http.get("/employee")
			// 			.then(result=>{
			// 				this.employees = result.data
			// 			})
			// 	},
			// 	getDeptTree(){
			// 		this.$http.get("/department/tree")
			// 			.then(result=>{
			// 				console.log("部门树：",result.data)
			// 				this.deptTree = result.data
			// 			})
			// 	}
			findParentDepts() {

				//发送异步post请求获取所有的上级部门
				this.$http.post("/dept/findParentDepts").then(res => {
					console.log(res)
					console.log(res.data.data)
					//赋值
					this.parentDepts = res.data.data;
				})
			},

			findManagers() {
				//发送异步post请求获取所有的部门经理
				this.$http.get("/emp/findManagers").then(res => {
					console.log(res)
					console.log(res.data.data)
					//赋值
					this.managers = res.data.data;
				})
			},
			getOptions() {
				this.$http.get("/emp").then(res => {
					console.log("22222222222222222222")
					console.log(res.data.data)
					this.employees = res.data.data;
				})

			},
			deptTreeList(){
				this.$http.get("/dept/treeList").then(res=>{
					console.log(res)
					console.log(res.data.data)
					this.treeList = res.data.data;
				})
			},

		},

		mounted() {  //页面加载的时候，执行
			this.getDepartments();
			//this.getEmps()
			//this.getDeptTree()
            //查询所有的上级部门
			this.findParentDepts();
			//获取所有的部门经理
			this.findManagers();
			//显示下拉框经理数据数据
			this.getOptions()
			//获取后台部门级联数据
			this.deptTreeList()
		}
	}

</script>

<style scoped>

</style>